package top.yzlin.jqueryjx3strategystation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.yzlin.jqueryjx3strategystation.dao.ArticleDAO;
import top.yzlin.jqueryjx3strategystation.entity.community.Article;
import top.yzlin.jqueryjx3strategystation.entity.user.User;
import top.yzlin.jqueryjx3strategystation.entity.vo.ResponseVO;

import java.util.Date;
import java.util.Optional;

@RestController
public class ArticleController {

    private ArticleDAO articleDAO;

    @Autowired
    public void setArticleDAO(ArticleDAO articleDAO) {
        this.articleDAO = articleDAO;
    }

    @GetMapping("/article/{articleId:\\d+}")
    public ResponseVO obtainArticleByUserNameAndArticleId(@PathVariable("articleId") Integer articleId) {
        Optional<Article> article = articleDAO.findById(articleId);
        return article.map(ResponseVO::createSuccessInstance).orElse(ResponseVO.NOT_FOUND);
    }

    @GetMapping("/article/list")
    public ResponseVO obtainArticle() {
        return ResponseVO.createSuccessInstance(articleDAO.findAll());
    }

    @PostMapping("/article/save")
    public ResponseVO saveArticle(Article article, @SessionAttribute("user") User user) {
        article.setDate(new Date(System.currentTimeMillis()));
        article.setUser(user);
        Article save = articleDAO.save(article);
        return ResponseVO.createInstance(200, "success", "/article/page.html?articleId=" + save.getArticleId());
    }


}
